package com.leantech.android.plugin

import com.android.build.api.dsl.ApplicationBaseFlavor
import com.android.build.api.variant.AndroidComponentsExtension
import org.gradle.api.Plugin
import org.gradle.api.Project
import java.io.File

class FlavorPlugin : Plugin<Project> {
    override fun apply(target: Project) {
        target.pluginManager.withPlugin("com.android.application"){
            val androidComponent = target.extensions.getByType(AndroidComponentsExtension::class.java)
            androidComponent.finalizeDsl { extension ->
                //create dimens.
                extension.flavorDimensions += "lean"
                extension.flavorDimensions += "abi"
                val flavors = getFlavors(File(target.rootDir, "config/project_config.json"))

                extension.productFlavors {
                    if (flavors.isNotEmpty()) {
                        flavors.forEach { (flavorName, projectInfo) ->
                            create(flavorName) {
                                if (this is ApplicationBaseFlavor) {
                                    dimension = "lean"
                                    applicationId = projectInfo.applicationId
                                    versionCode = projectInfo.versionCode()
                                    versionName = projectInfo.versionName
                                    resValue("string", "app_name", projectInfo.appName)
                                }
                            }
                        }
                    } else{
                        error("config/project_config.json is not define any flavors.")
                    }

                    create("abi32") {
                        dimension = "abi"
                        ndk {
                            abiFilters += "armeabi-v7a"
                        }
                    }

                    create("abi64") {
                        dimension = "abi"
                        ndk {
                            abiFilters += "arm64-v8a"
                        }
                    }

                    create("abi3264") {
                        dimension = "abi"
                        ndk {
                            abiFilters += "armeabi-v7a"
                            abiFilters += "arm64-v8a"
                        }
                    }
                }
            }
        }
    }
}